<template>
  <div>
    <BasicTable
      @register="registerTable"
      title="仓库信息管理"
      :pagination="false"
      :scroll="{ x: false, y: 'calc(100vh - 300px)' }"
    >
      <template #toolbar>
        <a-button type="primary" @click="onAddWareHouseButtonClick">新增</a-button>
      </template>
      <template #deptid="{ column, record }">
        {{
          treeToArray(deptData).filter((item) => item.key == record.deptid).length > 0
            ? treeToArray(deptData).filter((item) => item.key == record.deptid)[0].title
            : record.deptid
        }}
      </template>
      <template #action="{ column, record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditWareHouseButtonClick.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              label: '删除',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: onDeleteWareHouseButtonClick.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <AddOrUpdateWareHouse
      @register="registerAddOrUpdateWareHouseModal"
      :orgcode="orgcode"
      @success="afterSuccess"
    />
  </div>
</template>

<script lang="ts">
  import { defineComponent, onMounted, ref } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { useGlobSetting } from '/@/hooks/setting';
  import { Tag } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { queryAllWareHouse, deleteWareHouse } from '/@/api/ehs/warehouse';
  import { warehouseTableColumns } from './warehouse.data';
  import { getUserOrganization } from '/@/api/ehs/organization';
  import { getOrgDeptTree } from '/@/api/ehs/organization';
  import AddOrUpdateWareHouse from './AddOrUpdateWareHouse.vue';
  export default defineComponent({
    name: 'warehouseIndex',
    components: { BasicTable, TableAction, Tag, AddOrUpdateWareHouse },
    setup() {
      const deptData = ref([]);
      const orgcode = ref('');
      const { globalProjectCode } = useGlobSetting();
      const projectCode = ref<String>(globalProjectCode);
      const [registerAddOrUpdateWareHouseModal, { openModal: openAddOrUpdateWareHouse }] =
        useModal();
      const [registerTable, { reload }] = useTable({
        api: queryAllWareHouse,
        columns: warehouseTableColumns,
        canResize: true,
        striped: true,
        showTableSetting: true,
        showIndexColumn: true,
        isTreeTable: false,
        bordered: true,
        immediate: false,
        ellipsis: true,
        indexColumnProps: {
          width: 50,
        },
        beforeFetch: (params) => {
          params = orgcode.value;
          return params;
        },
        actionColumn: {
          width: 150,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });
      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        reload();
      }
      /**
       * 打开新增窗口
       */

      function onAddWareHouseButtonClick() {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '仓库管理',
          operateType: OperationTypeEnum.ADD,
          deptData: deptData.value,
        };
        openAddOrUpdateWareHouse(true, propsData);
      }
      /**
       * 打开编辑窗口
       * @param record
       */
      function onEditWareHouseButtonClick(record: TplWareHouseTreeTableItemDto) {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '仓库管理',
          operateType: OperationTypeEnum.EDIT,
          dataId: record.id,
          deptData: deptData.value,
        };
        openAddOrUpdateWareHouse(true, propsData);
      }

      /**
       * 删除
       * @param record
       */
      function onDeleteWareHouseButtonClick(record: TplWareHouseTreeTableItemDto) {
        deleteWareHouse(record.id)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              afterSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      // tree结构扁平化
      function treeToArray(treeNodes) {
        let result = [];

        //递归函数 traverse，用于处理单个节点
        function traverse(node, fatherId) {
          const newNode = { ...node };
          if (fatherId) {
            newNode.fatherId = fatherId;
          }
          delete newNode.children;
          // 将没有子节点的新节点添加到结果数组中
          result.push(newNode);

          // 如果当前节点包含 children 属性（即有子节点）
          if (node.children) {
            node.children.forEach((item) => {
              traverse(item, newNode.code);
            });
          }
        }

        treeNodes.forEach(traverse);

        return result;
      }

      onMounted(() => {
        getUserOrganization(globalProjectCode).then((res) => {
          orgcode.value = res.orgcode;
          getOrgDeptTree(res.orgcode)
            .then((res) => {
              if (res) {
                deptData.value = res;
              }
            })
            .catch((e) => {});
          reload();
        });
      });
      return {
        deptData,
        orgcode,
        treeToArray,
        registerAddOrUpdateWareHouseModal,
        registerTable,
        afterSuccess,
        onAddWareHouseButtonClick,
        onEditWareHouseButtonClick,
        onDeleteWareHouseButtonClick,
      };
    },
  });
</script>

<style scoped></style>
